package com.wn.study.repository

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.wn.study.repository.api.StudyService
import com.wn.study.repository.data.Daily2

/**
 * @Author: wn
 * @Date: 2023/7/14 17:05
 * @Description: PagingSource -- API
 */
//@ViewModelScoped
class StudyPagingSource /*@Inject constructor*/(private val studyService: StudyService) :
  PagingSource<Int, Daily2.Item>() {
  /**
   * Loading API for [PagingSource].
   */
  override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Daily2.Item> =
    runCatching {
      val currentPage = params.key ?: 1// 为空 就是第一页
      val pageSize = params.loadSize  // Pager-->PagingConfig 指定
      // API 获取数据
      val daily = studyService.getDailyApi2(currentPage, pageSize)

      val prevKey: Int?
      val nextKey: Int?
      val realPageSize = PAGE_SIZE
      if (currentPage == 1) {
        prevKey = null
        nextKey =
          pageSize / realPageSize + 1 // initialLoadSize = 16    1,16   3,8   4,8      相当于
      } else {
        prevKey = currentPage - 1
        // if(movies.movieList.isNotEmpty()) currentPage + 1 else null
        nextKey =
          if (daily.itemList.isNotEmpty()) currentPage + 1 else null// 没有下一页 就没有 nextKey
      }
      LoadResult.Page(daily.itemList, prevKey, nextKey)
    }.getOrElse {
      LoadResult.Error(it)
    }


  override fun getRefreshKey(state: PagingState<Int, Daily2.Item>): Int? = null
}